package problems.daily;

/**
 * 1694. 重新格式化电话号码
 * <p>https://leetcode.cn/problems/reformat-phone-number/</p>
 */
public class DT1694 {
    public String reformatNumber(String number) {
        char[] chs = number.toCharArray();
        int n = chs.length;
        int cnt = 0;

        for (int i = 0; i < n; ++i) {
            if (chs[i] >= '0' && chs[i] <= '9') {
                chs[cnt++] = chs[i];
            }
        }

        if (cnt < 2) return "";

        int k = 0;
        StringBuilder sb = new StringBuilder();

        while (k < cnt) {
            if (cnt - k > 4) {
                sb.append(String.valueOf(chs, k, 3)).append('-');
                k += 3;
            } else if (cnt - k == 4) {
                sb.append(String.valueOf(chs, k, 2))
                        .append('-')
                        .append(String.valueOf(chs, k + 2, 2));
                k += 4;
            } else {
                sb.append(String.valueOf(chs, k, cnt - k));
                k = cnt;
            }
        }

        return sb.toString();
    }
}
